package com.hp.process;

import com.hp.context.Config;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 接受发送数据
 */
public class SocketAction implements Runnable {
    Socket s;
    boolean run = true;
    private long receiveTimeDelay = 3000;
    long lastReceiveTime = System.currentTimeMillis();
    KeepAlive obj;

    public SocketAction(Socket s) {
        this.s = s;
    }

    public void run() {
        while (Server.running && run) {
            if (System.currentTimeMillis() - lastReceiveTime > receiveTimeDelay) {
                overThis();
            } else {
                try {
                    InputStream in = s.getInputStream();
                    if (in.available() > 0) {
                        ObjectInputStream ois = new ObjectInputStream(in);
                        obj = (KeepAlive) ois.readObject();//接受
                        /**************************************/
                        //检查任务
                        if (Server.datalist.get(obj.getId()) == null) {
                            Server.datalist.put(obj.getId(), obj);//添加或者覆盖
                        }
                        /**************************************/

                        lastReceiveTime = System.currentTimeMillis();
                        ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
                        oos.writeObject(Server.datalist.get(obj.getId()));//发送
                        oos.flush();
                        //如果任务发完就置false,没有也无所谓
                        obj.setFlag(false);
                        Server.datalist.put(obj.getId(), obj);
                    } else {
                        Thread.sleep(10);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    overThis();
                }
            }
        }
    }

    private void overThis() {
        if (run) run = false;
        if (s != null) {
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("email", Server.datalist.get(obj.getId()));
        Config.ac.getBean(MailSendQueueTask.class).getQueue().offer(map);

        Server.datalist.remove(obj.getId());//删除列表
        System.out.println("关闭：" + s.getRemoteSocketAddress());
    }

}
